package com.dragon.modules.yuegou.service.impl.act;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.act.AnnualRaffleEntity;
import com.dragon.modules.yuegou.entity.act.OffPrizeEntity;
import com.dragon.modules.yuegou.enums.code.ActivityCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.enums.order.OrderType;
import com.dragon.modules.yuegou.mapper.act.AnnualRaffleMapper;
import com.dragon.modules.yuegou.model.act.AnnualRaffle;
import com.dragon.modules.yuegou.model.act.GetActivityResponse;
import com.dragon.modules.yuegou.model.act.LotteryResultsResponse;
import com.dragon.modules.yuegou.model.act.OffActivity;
import com.dragon.modules.yuegou.model.act.SignIn;
import com.dragon.modules.yuegou.model.act.SignInResponse;
import com.dragon.modules.yuegou.model.member.Member;
import com.dragon.modules.yuegou.model.order.Goods;
import com.dragon.modules.yuegou.model.order.Order;
import com.dragon.modules.yuegou.properties.LotteryProperties;
import com.dragon.modules.yuegou.query.act.AnnualRaffleQuery;
import com.dragon.modules.yuegou.query.act.OffPrizeQuery;
import com.dragon.modules.yuegou.service.act.AnnualRaffleService;
import com.dragon.modules.yuegou.service.act.OffActivityService;
import com.dragon.modules.yuegou.service.act.OffPrizeService;
import com.dragon.modules.yuegou.service.act.SignInService;
import com.dragon.modules.yuegou.service.member.MemberService;
import com.dragon.modules.yuegou.service.order.GoodsService;
import com.dragon.modules.yuegou.service.order.OrderService;
import com.dragon.modules.yuegou.web.Check;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 年会抽奖 服务实现
 *
 * @author pbuilder generated
 * @date 2020-01-14 20:07:54
 * @version 2.0
 */
@Slf4j
@Service("actAnnualRaffleService")
public class AnnualRaffleServiceImpl
		extends ServiceImpl<AnnualRaffleMapper, AnnualRaffleEntity>
		implements AnnualRaffleService {
	protected static final String LOTTERY_RESULTS_CACHE_NAME = "LotteryResults";
	protected static final String LOTTERY_CONFIG_CACHE_NAME = "LotteryConfig";
	protected static final String LOTTERY_ACTIVITY_START = "LotteryActivityStart";

	@Autowired
	private OrderService orderService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private OffActivityService offActivityService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private SignInService signInService;
	@Autowired
	private OffPrizeService offPrizeService;
	@Autowired
	private LotteryProperties lotteryProperties;
	private Cache lotteryResultsCache;
	private Cache lotteryConfigCache;
	private Cache lotteryActivityStartCache;

	@Autowired
	public void setLotteryActivityStartCacheManager(CacheManager cacheManager) {
		this.lotteryActivityStartCache = cacheManager.getCache(LOTTERY_ACTIVITY_START);
	}

	@Autowired
	public void setLotteryResultsCacheManager(CacheManager cacheManager) {
		this.lotteryResultsCache = cacheManager.getCache(LOTTERY_RESULTS_CACHE_NAME);
	}

	@Autowired
	public void setLotteryConfigCacheManager(CacheManager cacheManager) {
		this.lotteryConfigCache = cacheManager.getCache(LOTTERY_CONFIG_CACHE_NAME);
	}

	@Override
	public AnnualRaffle getAnnualRaffleInfo(String mombile) {
		Check.notEmpty(mombile, SystemCode.MOBILE_NOTNULL.getMessage());
		AnnualRaffleQuery query = new AnnualRaffleQuery();
		query.setMobile(mombile);
		List<AnnualRaffleEntity> entities = baseMapper.selectList(query.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(entities)){
			return new AnnualRaffle(entities.get(0));
		}
		return new AnnualRaffle();
	}

	@Override
	@Transactional
	public SignInResponse signIn(String memberId) {
		Check.notEmpty(memberId, SystemCode.MOBILE_NOTNULL.getMessage());
		Member member = memberService.getMember(memberId);

		//是否已经签到
		boolean isSignIn = signInService.isSignIn(memberId);
		if (isSignIn) {
			throw new DragonException(ActivityCode.ALREADY_SIGN_IN);
		}

		//获取活动信息
		OffActivity offActivity = offActivityService.getActivity(getConfig().getActivityId());
		if (offActivity == null) {
			throw new DragonException(ActivityCode.ACTIVITY_NOT_EXIST);
		}

		SignInResponse response = new SignInResponse();
		//根据手机号查看用户是否在名单内
		AnnualRaffle annualRaffle = getAnnualRaffleInfo(member.getMobile());

		if (null != annualRaffle) {//在名单内,送券
			if (StringUtils.isBlank(annualRaffle.getOrderNo())) {
				//创建订单
				String skuId = getConfig().getEmployeeSkuId();
				if (annualRaffle.getIsLeader()) skuId = getConfig().getLeaderSkuId();
				Order order = orderService.createNullOrder(skuId, member.getId(), offActivity.getBusdId(), OrderType.LOTTERY, true,1);
				List<Goods> goodsList = order.getGoodsList();
				if (null != goodsList && goodsList.size() > 0) {
					response.setGoodsId(goodsList.get(0).getId());
				}
				response.setAnnualRaffle(annualRaffle);

				//更新订单号
				annualRaffle.setOrderNo(order.getId());
				annualRaffle.setModifiedTime(LocalDateTime.now());
				baseMapper.updateById(annualRaffle);
			}
		}

		//签到
		SignIn signIn = new SignIn();
		signIn.setId(IdWorker.getIdStr());
		signIn.setMemberId(member.getId());
		signIn.setMobile(member.getMobile());
		signInService.save(signIn);
		return response;
	}

	@Override
	public GetActivityResponse getActivity(String memberId) {
		Check.notEmpty(memberId, SystemCode.MOBILE_NOTNULL.getMessage());
		Member member = memberService.getMember(memberId);
		GetActivityResponse getActivityResponse = new GetActivityResponse();
		getActivityResponse.setActivityId(getConfig().getActivityId());

		//是否签到
		boolean isSignIn = signInService.isSignIn(memberId);
		getActivityResponse.setSignIn(isSignIn);

		if (isSignIn) {
			//根据手机号查看用户是否在名单内
			AnnualRaffle annualRaffle = getAnnualRaffleInfo(member.getMobile());
			if (null != annualRaffle) {//在名单内
				getActivityResponse.setAnnualRaffle(annualRaffle);
				String orderNo = annualRaffle.getOrderNo();
				if (StringUtils.isNotBlank(orderNo)) {
					String goodsId = goodsService.listByOrder(orderNo).get(0).getId();
					getActivityResponse.setGoodsId(goodsId);
				}
			}
		}
		return getActivityResponse;
	}

	@Override
	public LotteryResultsResponse getResult(String activityId) {
		Check.notEmpty(activityId, "活动Id不能为空");
		LotteryResultsResponse resultsResponse = lotteryResultsCache.get(activityId, LotteryResultsResponse.class);
		//从缓存返回
		if (null != resultsResponse) return resultsResponse;

		//没有缓存
		OffActivity offActivity = offActivityService.getActivity(activityId);
		if (offActivity == null) {
			throw new DragonException(ActivityCode.ACTIVITY_NOT_EXIST);
		}

		//查询活动下已开奖的奖品
		OffPrizeQuery prizeQuery = new OffPrizeQuery();
		prizeQuery.setActivityId(activityId);
		prizeQuery.setDel(false);
		QueryWrapper<OffPrizeEntity> wrapper = prizeQuery.toQueryWrapper();
		wrapper.orderByAsc(OffPrizeEntity.COL_PRICE);
		List<OffPrizeEntity> prizes = offPrizeService.list(wrapper);
		if (prizes != null && prizes.size() > 0) {
			OffPrizeEntity prize = prizes.get(0);
			resultsResponse = new LotteryResultsResponse();
			resultsResponse.setPrizeId(prize.getId());
			resultsResponse.setAllOver(false);
			resultsResponse.setGrade(prize.getGrade());
			resultsResponse.setStart(false);
			resultsResponse.setWinners(null);
			lotteryResultsCache.put(activityId, resultsResponse);
		}
		return resultsResponse;
	}

	@Override
	public void cacheResult(String activityId, LotteryResultsResponse result) {
		try {
			lotteryResultsCache.put(activityId, result);
		} catch (Exception e) {
			log.error("cacheResult出现错误=====>{},{}", e.getMessage(), e);
		}
	}

	@Override
	public LotteryProperties getConfig() {
		//从缓存获取
		LotteryProperties lotteryProperties = lotteryConfigCache.get("obj", LotteryProperties.class);
		if (null != lotteryProperties) return lotteryProperties;

		//从配置文件获取
		lotteryConfigCache.put("obj", lotteryProperties);
		return lotteryProperties;
	}

	@Override
	public void startActivityCache(String activityId) {
		try {
			lotteryActivityStartCache.put(activityId, Boolean.TRUE);
		} catch (Exception e) {
			log.error("startActivityCache出现错误=====>{},{}", e.getMessage(), e);
		}
	}

	@Override
	public Boolean isStartActivity(String activityId) {
		try {
			Boolean isStart = lotteryActivityStartCache.get(activityId, Boolean.class);
			if (null != isStart && isStart)
				return isStart;
		} catch (Exception e) {
			log.error("startActivityCache出现错误=====>{},{}", e.getMessage(), e);
		}
		return false;
	}
}